package com.wsw.aitools.utils;

import org.springframework.util.Base64Utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ImageUtils {

    public static String encodeImage(String imagePath) {
        byte[] imageBytes = null;
        try {
            imageBytes = Files.readAllBytes(Paths.get(imagePath));
        } catch (IOException e) {
            
            throw new RuntimeException(e);
        }
        String base64 = Base64Utils.encodeToString(imageBytes);

        // 需要注意：传入Base64编码前需要增加前缀 data:image/{图片格式};base64,{Base64编码}：
        // PNG图片："url":  f"data:image/png;base64,{base64_image}"
        // JEPG图片："url":  f"data:image/jpeg;base64,{base64_image}"
        // WEBP图片："url":  f"data:image/webp;base64,{base64_image}"

        // 判断图片格式
        String format = imagePath.substring(imagePath.lastIndexOf(".") + 1);
        switch (format) {
            case "png":
                return "data:image/png;base64," + base64;
            case "jpeg":
                return "data:image/jpeg;base64," + base64;
            case "jpg":
                return "data:image/jpg;base64," + base64;
            case "webp":
                return "data:image/webp;base64," + base64;
            default:
                return "data:image/png;base64," + base64;
        }
    }
}
